from flask import Blueprint, request, current_app
from flask_restx import Resource, Namespace, fields
from app.services.banner_service import BannerService
from app.utils.response import success_response, error_response

# 创建蓝图
banners_bp = Blueprint('banners_v1', __name__, url_prefix='/api/v1')

# 创建命名空间
banners_ns = Namespace('banners', description='轮播图接口')

# 定义响应模型
banner_model = banners_ns.model('Banner', {
    'id': fields.Integer(description='ID'),
    'title': fields.String(description='标题'),
    'image': fields.String(description='图片URL'),
    'link': fields.String(description='跳转链接'),
    'type': fields.Integer(description='类型 1首页 2分类'),
    'sort': fields.Integer(description='排序'),
    'create_datetime': fields.String(description='创建时间')
})

@banners_ns.route('/banners')
class BannerListAPI(Resource):
    """轮播图列表接口 - 无需认证"""
    
    def get(self):
        """获取轮播图列表"""
        try:
            # 默认获取首页轮播图(type=1)，且只获取启用状态的
            banner_type = request.args.get('type', 1, type=int)
            
            # 调试输出
            current_app.logger.info(f"获取轮播图，类型: {banner_type}")
            
            # 调用Service获取轮播图列表，不需要分页
            banners, total = BannerService.list_banners(banner_type=banner_type, page=1, limit=100)
            
            # 调试输出
            current_app.logger.info(f"获取到 {len(banners)} 条轮播图数据, 总数: {total}")
            for banner in banners:
                current_app.logger.info(f"Banner: {banner}")
            
            # 只返回启用状态的轮播图
            active_banners = [banner for banner in banners if banner.get('status') is True]
            current_app.logger.info(f"筛选后的启用轮播图: {len(active_banners)} 条")
            
            return success_response(data=active_banners, message='获取成功')
        except Exception as e:
            current_app.logger.error(f"获取轮播图失败: {str(e)}")
            import traceback
            current_app.logger.error(traceback.format_exc())
            return error_response(f"获取轮播图失败: {str(e)}", 500)

# 注册命名空间
from app.api.v1 import api
api.add_namespace(banners_ns, path='/banners')

# 在__init__.py中注册蓝图 